package com.example.chatrecycle.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.example.chatrecycle.adapter.MyRecyclerViewAdapter;
import com.example.chatrecycle.databinding.FragmentChatBinding;
import com.example.chatrecycle.model.MsgEntity;
import com.example.chatrecycle.viewmodel.ChatMessageItemViewModel;

import java.util.List;

/**
 *
 */
public class ChatFragment extends Fragment {

    FragmentChatBinding chatBinding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        chatBinding = FragmentChatBinding.inflate(inflater, container, false);
        // Inflate the layout for this fragment
        ChatMessageItemViewModel chatMessageItemViewModel = new ChatMessageItemViewModel();
        //判断当前RecycleView是否有适配器
        if (chatBinding.rv.getAdapter() == null) {
            //创建适配器
            MyRecyclerViewAdapter myRecyclerViewAdapter = new MyRecyclerViewAdapter(chatMessageItemViewModel.getMsgs());
            chatBinding.rv.setAdapter(myRecyclerViewAdapter);
            chatBinding.rv.setLayoutManager(new LinearLayoutManager(getContext()));
        } else {
            //这一句好像没什么用
            chatBinding.rv.getAdapter().notifyDataSetChanged();
        }


        //点击事件
        chatBinding.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String state = chatBinding.state.getText().toString();
                String msg = chatBinding.msg.getText().toString();
                MsgEntity msgEntity = new MsgEntity(Integer.valueOf(state), msg);


                //这里Viewmodel中的可观察对象发生变化，之后页面没有发生变化，难道是要用Mul
                List<MsgEntity> msgEntities = chatMessageItemViewModel.getMsgs().get();
                msgEntities.add(msgEntity);
                chatMessageItemViewModel.getMsgs().set(msgEntities);
                //这时候被观察对象数据应该已经变化了，通知adapter更新数据
                chatBinding.rv.getAdapter().notifyItemInserted(msgEntities.size() - 1); //刷新列表中的展示
                //列表定位到最后一行
                chatBinding.rv.scrollToPosition(msgEntities.size() - 1);
            }
        });
        return chatBinding.getRoot();
    }
}